package com.online.usermanagesystem.utils.accessrule;

/**
 * @author jhk
 */

public class Accessible {

    public static String mode(String operator, String group, Rule rule) {
        boolean other = true;
        char mode[] = new char[2];
        if ((null != operator) && (operator == rule.owner())) {
            mode[0] = rule.mode().charAt(0);
            mode[1] = rule.mode().charAt(1);

            other = false;
        } else {
            mode[0] = '-';
            mode[1] = '-';
        }

        if ((null != group) && (group == rule.group())) {
            if (mode[0] < rule.mode().charAt(2)) {
                mode[0] = rule.mode().charAt(2);
            }

            if (mode[1] < rule.mode().charAt(3)) {
                mode[1] = rule.mode().charAt(3);
            }

            other = false;
        }

        if (other) {
            mode[0] = rule.mode().charAt(4);
            mode[1] = rule.mode().charAt(5);
        }

        return mode.toString();
    }

    public static boolean read(String operator, String group, Rule rule) {
        return 'r' == mode(operator, group, rule).charAt(0);
    }

    public static boolean write(String operator, String group, Rule rule) {
        return 'w' == mode(operator, group, rule).charAt(1);
    }

    public static boolean none(String operator, String group, Rule rule) {
        return "--".equals(mode(operator, group, rule));
    }

    public static boolean read(String operator, String group, Object obj) {

        Rule rule = obj.getClass().getAnnotation(Rule.class);
        if (null == rule) {
            return true;
        }

        return read(operator, group, rule);
    }

    public static boolean write(String operator, String group, Object obj) {

        Rule rule = obj.getClass().getAnnotation(Rule.class);
        if (null == rule) {
            return true;
        }

        return write(operator, group, rule);
    }

    public static boolean none(String operator, String group, Object obj) {
        Rule rule = obj.getClass().getAnnotation(Rule.class);
        if (null == rule) {
            return true;
        }

        return none(operator, group, rule);
    }
}
